package com.game.sdk.view;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.game.sdk.YTAppService;
import com.game.sdk.db.impl.UserLoginInfodao;
import com.game.sdk.domain.LoginErrorMsg;
import com.game.sdk.domain.LogincallBack;
import com.game.sdk.domain.OnLoginListener;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.domain.UserInfo;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.login.LoginUtils;
import com.game.sdk.util.Constants;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.Logger;
import com.game.sdk.util.MResource;
import com.game.sdk.util.ThreadPoolManager;
import com.game.sdk.util.Util;

/**
 * author janecer 2014年7月21日下午5:03:45
 */
public class RegisterView extends BaseView {
	public static Activity acontext;
	private UserInfo userinfo;
	private String uname = "";
	private SharedPreferences sp;
	private EditText et_username, et_pwd, et_code;
	private Button btn_game_in, btn_send_code; // 注册，发送验证码

	TimeCount time;
	public static boolean isSelfRegister = false; // 用来标记是否是自定义注册 调整到登录页面的
	public static String username, pwd;
	private static OnLoginListener loginListener;// 登录回调监听
	private LinearLayout ll_back_user_login, ll_user_oneregister_goin,
			ll_user_register_goin;
	private boolean isPortrait;// 是否是竖版

	/**
	 * 构造方法 用来示例view对象
	 * 
	 * @param ctx
	 */
	public RegisterView(Activity ctx, OnLoginListener logininlist) {
		time = new TimeCount(60000, 1000);// 构造CountDownTimer对象
		acontext = ctx;
		inflater = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		loginListener = logininlist;
		isPortrait = (acontext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);

		if (isPortrait) {
			content_view = inflater.inflate(MResource.getIdByName(ctx,
					Constants.Resouce.LAYOUT, "sdk_tel_register"), null);
		} else {
			content_view = inflater.inflate(MResource.getIdByName(ctx,
					Constants.Resouce.LAYOUT, "sdk_tel_register_landscape"),
					null);
		}

		initData();

		et_code = (EditText) content_view.findViewById(MResource.getIdByName(
				ctx, Constants.Resouce.ID, "et_code"));
		et_username = (EditText) content_view.findViewById(MResource
				.getIdByName(ctx, Constants.Resouce.ID, "et_username"));
		et_pwd = (EditText) content_view.findViewById(MResource.getIdByName(
				ctx, Constants.Resouce.ID, "et_pwd"));

		// 用户协议
		// tv_user_aggrement = (TextView) content_view.findViewById(MResource
		// .getIdByName(ctx, Constants.Resouce.ID, "tv_user_aggrement"));
		btn_game_in = (Button) content_view.findViewById(MResource.getIdByName(
				ctx, Constants.Resouce.ID, "btn_game_in"));

		btn_send_code = (Button) content_view.findViewById(MResource
				.getIdByName(ctx, Constants.Resouce.ID, "btn_send_code"));
		ll_back_user_login = (LinearLayout) content_view.findViewById(MResource
				.getIdByName(ctx, Constants.Resouce.ID, "ll_back_user_login"));
		ll_user_oneregister_goin = (LinearLayout) content_view
				.findViewById(MResource.getIdByName(ctx, Constants.Resouce.ID,
						"ll_user_oneregister_goin"));
		ll_user_register_goin = (LinearLayout) content_view
				.findViewById(MResource.getIdByName(ctx, Constants.Resouce.ID,
						"ll_user_register_goin"));

		btn_game_in.setOnClickListener(this);
		btn_send_code.setOnClickListener(this);
		et_username.setText(uname);
		sp = acontext.getSharedPreferences(Constants.CONFIG,
				Context.MODE_PRIVATE);
	}

	/**
	 * 初始化相关数据
	 */
	private void initData() {
		userinfo = new UserInfo();
		TelephonyManager tm = (TelephonyManager) acontext
				.getSystemService(Context.TELEPHONY_SERVICE);
		userinfo.imeil = tm.getDeviceId();
		userinfo.deviceinfo = tm.getLine1Number() + "||android"
				+ Build.VERSION.RELEASE;

		userinfo.agent = YTAppService.agentid;
	}

	public void setOnClick(OnClickListener onclick) {
		ll_back_user_login.setOnClickListener(onclick);
		ll_user_oneregister_goin.setOnClickListener(onclick);
		ll_user_register_goin.setOnClickListener(onclick);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == MResource.getIdByName(acontext, Constants.Resouce.ID,
				"btn_game_in")) {
			final String username = et_username.getText().toString().trim();
			final String password = et_pwd.getText().toString().trim();
			String sendcode = et_code.getText().toString().trim();
			Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
			Pattern p = Pattern.compile("[1][1234567890]\\d{9}");
			Matcher pipeMatcher = p.matcher(username);
			if (!pipeMatcher.matches()) {

				Toast.makeText(acontext, "手机号码输入不正确，请重新输入！", Toast.LENGTH_SHORT)
						.show();

				return;
			}
			if (TextUtils.isEmpty(sendcode)) {
				Toast.makeText(acontext, "请输入验证号", Toast.LENGTH_SHORT).show();
				return;
			}
			if (TextUtils.isEmpty(username)) {
				Toast.makeText(acontext, "请输入手机号", Toast.LENGTH_SHORT).show();
				return;
			}
			if (TextUtils.isEmpty(password)) {
				Toast.makeText(acontext, "请输入密码", Toast.LENGTH_SHORT).show();
				return;
			}

			if (password.length() < 6 || password.length() > 16
					|| pat.matcher(password).find()) {
				Toast.makeText(acontext, "密码只能由6至16位16位英文或数字组成",
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (null == userinfo) {
				initData();
			}

			userinfo.issend = 0;
			userinfo.sendcode = sendcode;
			userinfo.username = username;
			userinfo.password = password;
			DialogUtil.showDialog(acontext, "正在注册帐号...");
			// new RegisterAsyTask().execute();
			LoginUtils.registMsg(username, password, sendcode, "1", acontext,
					new NetCallBack() {

						@Override
						public void onInitSuccess(ResultCode result) {
							String data = result.data;
							if (!TextUtils.isEmpty(data)) {
								try {
									JSONObject o = new JSONObject(data);
									int mem_id = (Integer) o.get("a");
									String user_token = o.getString("b");
									if (!UserLoginInfodao.getInstance(acontext)
											.findUserLoginInfoByName(username)) {
										UserLoginInfodao.getInstance(acontext)
												.saveUserLoginInfo(username,
														password);
									} else {
										UserLoginInfodao
												.getInstance(acontext)
												.deleteUserLoginByName(username);
										UserLoginInfodao.getInstance(acontext)
												.saveUserLoginInfo(username,
														password);
									}

									Editor editor = sp.edit();
									editor.putBoolean(
											Constants.ISFIRST_INSTALL, false);
									editor.commit();

									LogincallBack loginCallback = new LogincallBack();
									YTAppService.isLogin = true;
									YTAppService.userinfo = userinfo;
									YTAppService.userinfo.mem_id = mem_id + "";
									YTAppService.userinfo.user_token = user_token;

									loginCallback.mem_id = mem_id + "";
									loginCallback.user_token = GetDataImpl.PHPSESSID;
									// loginCallback.username = username;
									loginListener.loginSuccess(loginCallback);// 回调登录成功
								} catch (JSONException e) {
									e.printStackTrace();
									Util.showNetFailToast(acontext, "服务器格式不对",
											null);
								}
							} else {
								Util.showNetFailToast(acontext, "服务器没有数据给我们",
										null);
							}
							acontext.finish();
						}

						@Override
						public void onInitFail(ResultCode result) {
							Util.showNetFailToast(acontext, "注册失败", result);
						}
					});
		}
		if (v.getId() == MResource.getIdByName(acontext, Constants.Resouce.ID,
				"btn_send_code")) {

			String usertelephone = et_username.getText().toString().trim();
			userinfo.username = usertelephone;
			userinfo.issend = 1;
			LoginUtils.registMsg(usertelephone, pwd, "", "0", acontext,
					new NetCallBack() {

						@Override
						public void onInitSuccess(ResultCode result) {
							if (result.code == 1) {
								time.start();
							}
							Util.showNetFailToast(acontext, "获取验证码失败", result);
						}

						@Override
						public void onInitFail(ResultCode result) {
							Util.showNetFailToast(acontext, "获取验证码失败", result);
						}
					});
		}

	}

	@Override
	public View getContentView() {
		return content_view;
	}

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔

		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_send_code.setText("重新发送");
			btn_send_code.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_send_code.setClickable(false);
			btn_send_code.setText(millisUntilFinished / 500 + "秒");
		}
	}
}
